#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: Florian Dorn <florian.dorn@gmail.com>
# @package: agenda
# @license: GNU GPLv2
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

from gettext import gettext as _

import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
import gobject

import dbus
import dbus.service
import dbus.gobject_service
import dbus.glib

import cgi
import datetime

try:
	import sexy
except ImportError:
	sexy = None
try:
	import pynotify
except:
	pynotify = None

import agenda

from agenda import Keybinder
from agenda import Filter
from agenda.appointment import *
from agenda.pluginsystem import *
from agenda.ui.AgendaWindow import AgendaWindow
from agenda.ui.EditEventWindow import EditEventWindow
from agenda.ui.AgendaListView import  AgendaListView
from agenda.ui.iCalTimeEdit import  iCalTimeEdit


from agenda.ui.PrefDialog import PrefDialog
from agenda.ui.ProgressWidget import ProgressWidget

from agenda.ui.SearchAddBar import SearchAddBar

import datetime


def override_expose(self, event, palette = "BASE"):
		allocation = self.get_allocation()
		style = self.get_style()
		state = self.state
		if palette == 'BASE':
			gc = style.base_gc[state]
		elif palette == 'BG':
			gc = style.bg_gc[state]
		elif palette == 'FG':
			gc = style.fg_gc[state]
		else:
			gtk.VBox.do_expose_event(self, event)
			return
		self.window.draw_rectangle(gc, True, allocation.x, allocation.y, allocation.width, allocation.height)
		gtk.VBox.do_expose_event(self, event)
		pass

class Agenda(dbus.gobject_service.ExportedGObject):
	VIEW_CALENDAR = 0
	VIEW_ASK = 1
	VIEW_EDIT = 2
	__gsignals__ = {
		'updated-event-store' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,[gobject.TYPE_PYOBJECT]),
		'initialized'  : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,[]),
		'nothing-found' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,[]),
	}
	updating = False
	
	DEFAULT_KEYBINDING = "<Alt>F12"
	aboutdialog = None	

	def add_event_cancel_cb(self,a=None,c=None,b=None,d=None):
		self.change_view(Agenda.VIEW_CALENDAR)

	def reset_addview(self):
		if self.__addview_initialized:
			self.edit_what.set_text("")
			self.edit_where.set_text("")
			self.edit_desc.set_buffer(gtk.TextBuffer())
			self.edit_date.reset()
	def add_event_ok_cb(self,a=None,c=None,b=None,d=None):
		"""
		add an event
		"""
		#@TODO: get the selected claendar. for now just use the default google calendar
		try:
			calendar = self.__calendar_model[self.edit_calendar.get_active()][0]
			#calendar = #self.appointments.tmp_get_google_cal_default()
			#calendar = self.edit_calendar.
			print "calendar %s" % calendar
			
			what = self.edit_what.get_text()
			where = self.edit_where.get_text()
			start_time = self.edit_date.get_start()
			end_time = self.edit_date.get_end()
			b = self.edit_desc.get_buffer()
			desc = b.get_text(b.get_start_iter(),b.get_end_iter())
			recurrence_data = None #self.edit_date.get_rruleset()
			
			self.appointments.create_event(calendar, what,start_time,end_time,where,desc,recurrence_data)
			
		except Exception,e:
			import traceback
			print traceback.print_exc()
			
			
		self.change_view(Agenda.VIEW_CALENDAR)
		
	def on_view_set_page_cb(self,notebook,page,page_num=None):
		self.change_view(page_num)
		pass
	def change_view(self,view):
		if (view == self.__current_view):
			return

		if(self.__current_view == Agenda.VIEW_EDIT):
			self.reset_addview()

		self.__current_view = view
		#@todo: populate the edit view, and clean it up again on close
		if view == Agenda.VIEW_CALENDAR:
			self.wTree.get_widget("switch_add_button").set_active(False)
			self.cal_edit_notebook.set_current_page(view)
			#add_item_panel = self.wTree.get_widget("add_item_panel")
			#add_item_panel.hide()
			add_item_ask = self.wTree.get_widget("add_item_ask")
			add_item_ask.show()
			#self.filterEntry.set_type(SearchAddBar.TYPE_FILTER)
			self.filterEntry.grab_focus()
			self.filterEntry.set_text("")
		elif view == Agenda.VIEW_EDIT:
			self.wTree.get_widget("switch_add_button").set_active(True)
			self.cal_edit_notebook.set_current_page(view)
			self.init_addview()
		elif view == Agenda.VIEW_ASK:
			self.filterEntry.grab_focus()
			self.wTree.get_widget("switch_add_button").set_active(False)
			self.cal_edit_notebook.set_current_page(view)
	def on_add_page_key_press_event(self,panel,data):
		keyname = gtk.gdk.keyval_name(data.keyval)
		if keyname == "Escape":
			self.change_view(Agenda.VIEW_CALENDAR)
	def on_filter_type_changed(self,filterEntry,f_type):
		#if f_type == SearchAddBar.TYPE_FILTER:
		#	self.change_view(Agenda.VIEW_CALENDAR)
		#if f_type == SearchAddBar.TYPE_ADD:
		#	self.change_view(Agenda.VIEW_ASK)
		pass
	def init_addview(self):
		if(not self.__addview_initialized):
			self.edit_what = self.wTree.get_widget("edit_what")
			self.edit_desc = self.wTree.get_widget("edit_desc")
			self.edit_where = self.wTree.get_widget("edit_where")
			self.edit_calendar = self.wTree.get_widget("combo_calendar")
			
			#todo: keep the model in sync with the actual calendars
			cell = gtk.CellRendererText()
			self.edit_calendar.pack_start(cell, True)
			self.edit_calendar.add_attribute(cell, 'text', 1)

			self.edit_date = iCalTimeEdit()
			editDlgTable = self.wTree.get_widget("editDlgTable")
			editDlgTable.attach(self.edit_date,1,2,1,2)
			self.__addview_initialized = True
			pass
		print "updating model"
		__calendar_model = gtk.ListStore(gobject.TYPE_PYOBJECT,str)
		for calendar in self.appointments.item_storage.get_calendars():
			if calendar.is_visible() and calendar.is_writeable():
				print "adding %s" % calendar
				__calendar_model.append( [calendar,calendar.get_name() ] )
		self.__calendar_model = __calendar_model
		self.edit_calendar.set_model(self.__calendar_model)
		self.edit_calendar.set_active(0)

	def switch_add_button_toggled_cb(self,toggle_btn):
		if(toggle_btn.get_active()):
			self.change_view(Agenda.VIEW_EDIT)
		else:
			self.change_view(Agenda.VIEW_CALENDAR)
	def __init__(self, bus, path, name):
		#dbus.gobject.Object.__init__ (self, bus, path, name)
		
		dbus.gobject_service.ExportedGObject.__init__ (self, bus, path)
		
		self.running = False
		
		self.prefs = None
		self.__addview_initialized = False
		self.appointments =  Appointments()
		#start the DB thread
		
		
		self.appointments.connect('updating-calendars-finished',self.appointments_calendars_updated_cb)
		self.appointments.connect('updating-calendars-start',self.appointments_updating_calendars)
		#self.appointments.connect('updating-calendars-tick',self.appointments_updating_tick)
		self.appointments.connect('updating-provider-started',self.appointments_updating_provider)
		
		
		self.appointments.connect('updated-event-store',self.event_store_updated)
		self.appointments.connect('close',self.on_appointments_closed)
		
		self.appointments.connect('first-time-usage',self.on_first_time_usage_cb)


		self.appointments.start()

		self.connect('initialized',self.on_initialized_cb)
		self.connect('nothing-found', self.on_nothing_found_cb)
		#calendars_updated_cb
		"""window is hidden on startup"""
		#The last searched Term
		#hide finished events
		self.hide_finished = True
		#hold the timeout-ids for refreshing/alerting
		self.timeout_refresh = -1
		self.timeout_alert = -1



		self.__current_view = None

		#self.notify_tooltip = None
		#try:
		#	self.pynotify_ok = pynotify.init(agenda.APP_NAME)
		#except:
		#	self.pynotify_ok = False
					
		#stores event-ids that ahe already been notified
		self.notified_ids = []
		#Set the Glade file

		self.wTree = gtk.glade.XML(agenda.GLADEFILE)
		
		self.__base_icon_pixbuf = agenda.load_stock_image("x-office-calendar",gtk.ICON_SIZE_SMALL_TOOLBAR)
		
		self.statusIcon = gtk.StatusIcon()
		self.window = AgendaWindow(self.statusIcon)
		
		panel = self.wTree.get_widget("panel")
		panel.reparent(self.window)
		panel.set_border_width(0)
		
		#self.wTree.get_widget("i_am_white").modify_bg(panel.state,panel.style.base[gtk.STATE_NORMAL])
		#self.wTree.get_widget("i_am_white").do_expose_event = override_expose
		
		self.wTree.get_widget("i_am_white").connect("expose-event",override_expose)
		
		
		self.statusIcon.set_tooltip("%s" % _(agenda.static.APP_NAME))
		self.statusIcon.connect('popup-menu', self.popup_menu_cb)
		self.statusIcon.connect('activate', self.status_icon_click_cb)		
		self.statusIcon.connect('size-changed', self.status_icon_size_changed_cb)

		search_container = self.wTree.get_widget("search_container")
		

		self.filterEntry = SearchAddBar()
		self.filterEntry.show()
		self.filterEntry.connect("filter-changed", self.on_filterEntry_changed)
		self.filterEntry.connect("add-event", self.addEventBtn_activate_cb)
		self.filterEntry.connect("add-event", self.show_add_item_panel)

		self.filterEntry.connect("type-changed", self.on_filter_type_changed)

		search_container.add(self.filterEntry)

		
		self.refresh_menuitem = self.wTree.get_widget("refresh")
		
		self.cal_edit_notebook = self.wTree.get_widget("cal_edit_notebook")
		self.cal_edit_notebook.set_show_tabs(False)
		self.cal_edit_notebook.connect("switch-page",self.on_view_set_page_cb)
		
		

			
		#Connect to the signals
		self.wTree.signal_autoconnect(self)
		
		self.window.connect("configure-event",self.on_window_configure_cb)
		self.window.connect("button-press-event",self.main_button_press_event_cb)
		#the global widgets
		
		
		self.error_indicator = self.wTree.get_widget("error_indicator")
		self.popup_menu = self.wTree.get_widget("popup_menu")
		#self.search_entry = self.wTree.get_widget("search_entry")
		self.errors_label = self.wTree.get_widget("errors_label")



		self.calendar = AgendaListView(self.appointments)
		cal_viewport = self.wTree.get_widget("cal_viewport")
		cal_viewport.add(self.calendar)

		#cal_viewport.modify_bg(cal_viewport.state, cal_viewport.style.white)			

		#self.wTree.get_widget("add_page").modify_bg(cal_viewport.state, cal_viewport.style.white)
	
		progress_container = self.wTree.get_widget("statusbar")
		self.progressbar = ProgressWidget()
		self.progressbar.connect("pixbuf-changed",self.progress_widget_changed)
		progress_container.pack_start(self.progressbar)
		statusbar = self.wTree.get_widget("statusbar")

		
		#hide the frame of the statusbar
		frame = None
		for w in statusbar.get_children():
			if isinstance(w,gtk.Frame):
				w.hide()

		if(Keybinder):
			try:
				self._setup_keybinder()
			except:
				#LOGGER.error("could not setup keybinder")
				pass
		self.emit('initialized')

		self.change_view(Agenda.VIEW_CALENDAR)

		self.set_icon_pixbuf(self.__base_icon_pixbuf)
		self.statusIcon.set_visible(True)
		
		self.window.ensure_style()	#make sure we have a style (minimized windows don't so the theme won't be changed
		self._style_source = self.window.connect ("notify::style", self.theme_changed_cb) # gtk theme changes

		
	def theme_changed_cb(self, obj=None, prop=None):
		self.__base_icon_pixbuf = agenda.load_stock_image("x-office-calendar",gtk.ICON_SIZE_SMALL_TOOLBAR)
		self.set_icon_pixbuf( self.__base_icon_pixbuf )

	def progress_widget_changed(self,progresswidget,pixbuf):
		"""
		update the app icon to indicate updating state
		"""
		if pixbuf:
			#tmppixbuf = self.__base_icon_pixbuf.copy()
			tmppixbuf = pixbuf.copy()
			#tmppixbuf.saturate_and_pixelate(tmppixbuf,0,False)
			p_width, p_height = pixbuf.get_width(), pixbuf.get_height()
			p_width = p_width/2
			width, height = tmppixbuf.get_width(), tmppixbuf.get_height()
			self.__base_icon_pixbuf.composite(tmppixbuf,0,0,width,height,0,0,1,1,gtk.gdk.INTERP_NEAREST,48)
			self.set_icon_pixbuf(tmppixbuf)
			self.window.set_icon(tmppixbuf)
		else:
			tmppixbuf = self.__base_icon_pixbuf
		self.set_icon_pixbuf( tmppixbuf )


	def set_icon_pixbuf(self,pixbuf):
		self.statusIcon.set_from_pixbuf(pixbuf)
		self.window.set_icon( pixbuf )
		#self.window.queue_draw()
	@dbus.service.method("org.domain.GnomeAgenda")
	def ShowMainWindow(self):
		self.window.show_window()
	@dbus.service.method("org.domain.GnomeAgenda")
	def updateCalendars(self):
		self.appointments.updateCalendars()
	@dbus.service.method ("org.domain.GnomeAgenda", in_signature='a{sv}', out_signature='')
	def start(self,options):
		if(options['update']):
			self.updateCalendars()
		if self.is_running ():
			self.window.show_window()
		else:
			self.running = True
			try :
				gtk.main ()
			except:
				pass
			self.running = False
			self.appointments.stop()

	@dbus.service.method ("org.domain.GnomeAgenda", in_signature='', out_signature='b')
	def is_running(self,):
		return self.running	
	def toggle_search_btn_toggled_cb(self,widget,filterEntry):
		active = widget.get_active()
		
		self.wTree.get_widget("search_alignment").set_property("visible",active)
		if(active):
			self.filterEntry.grab_focus()
		else:
			self.searchBox_clear(widget,filterEntry)
	def about_icon_cb(self,widget):
		"""
		About clicked
		"""
		if(self.aboutdialog == None):
			self.aboutdialog = self.wTree.get_widget("aboutdialog")
			self.aboutdialog.set_version(agenda.static.APP_VERSION)
			self.aboutdialog.set_program_name(_(agenda.static.APP_NAME))
		self.aboutdialog.run()
		self.aboutdialog.hide()
		
		pass
	
	def settings_activate_cb(self,widget = None):
		"""
		Show the preference dialog
		"""
		if self.prefs:
			self.prefs.present()
			return
		self.prefs = PrefDialog(self.appointments,self)
		
		result = self.prefs.run()
		self.prefs = None

		pass
	def on_first_time_usage_cb(self,appointments):
		gobject.idle_add(self.settings_activate_cb)

	def show_notify_tooltip(self):
		pass
	#	#print "show_notify_tooltip"
	#	#print self.notify_tooltip
	#	if(not self.notify_tooltip):
	#		self.notify_tooltip = pynotify.Notification(agenda.APP_NAME,"","x-office-calendar")
	#		self.notify_tooltip.set_urgency(pynotify.URGENCY_LOW)
	#		self.notify_tooltip.set_timeout(pynotify.EXPIRES_NEVER)
	#		self.notify_tooltip.attach_to_widget(self.statusIcon)
	#		self.notify_tooltip.connect("closed",self.close_notify_tooltip_cb)
	#		self.notify_tooltip.show()
	def hide_notify_tooltip(self):
		pass
	#	#print "hide_notify_tooltip"
	#	if(self.notify_tooltip):
	#		self.notify_tooltip.close()
	#	self.notify_tooltip = None

	def close_notify_tooltip_cb(self):
		self.hide_notify_tooltip()
	def popup_menu_cb(self,widget, button = 3, time= 0, data = None):
		"""
		right click on the status icon
		"""
		if (time == 0):
			time = gtk.get_current_event_time()
		if(type(self.statusIcon) == gtk.StatusIcon and self.statusIcon.get_geometry()):
			self.popup_menu.popup(None, None, gtk.status_icon_position_menu, button, time,self.statusIcon)
		elif(True):
			self.popup_menu.popup(None, None, widget.tray_icon_position_menu, button, time,self.statusIcon)
		else:
			self.popup_menu.popup(None, None, None, button, time,self.statusIcon)
	

	def status_icon_click_cb(self,widget=None,menu=None):
		"""
		left click on the status icon
		"""

		self.window.show_window()
	def status_icon_size_changed_cb(self,statusicon,size):
		pass
	
	def menu_position_func(self,menu,data):
		event = data[0]
		widget = data[1]
		x,y = int(event.x_root+1), int(event.y_root+1)

		return (x,y,True)
	def on_window_configure_cb(self,widget, event):
		size = self.window.get_size()
		cur_width = self.appointments.get_option('width')
		cur_height = self.appointments.get_option('height')
		
		if(cur_width != size[0] or cur_height != size[1]):
			self.appointments.set_option('width',max(0,int(size[0])))
			self.appointments.set_option('height',max(0,int(size[1])))
	def main_button_press_event_cb(self, widget=None,event = None,data = None):
		if ((data == None and event.button == 3) or (data != None and event.button == 1)):
			self.popup_menu.popup(None, None, self.menu_position_func, event.button, event.time,(event,data))

		return True
		pass
	def main_destroy_event_cb(self,widget, data=None):
		##do not call quit() since, the window will be destroyed, and the size/position is not valid anymore
		gtk.main_quit()
	def searchBox_clear(self,widget,filterEntry):
		
		if(filterEntry.get_text() != ""):
			filterEntry.set_text("")
			self.search_entry_activate_cb(None,filterEntry)
	def search_entry_activate_cb(self,widget,filterEntry):
		"""
		Perform the search if "ENTER" was hit
		"""
		SearchTerm = self.filterEntry.get_text()
		self.filter(SearchTerm)

	def filter(self,SearchTerm = ""):
		if(not type(SearchTerm) in (str,unicode) ):
			SearchTerm = ""
		filter = Filter(SearchTerm)
		now = datetime.datetime.now()
		
		ret = self.calendar.filter(filter)
		
		#disabled adding events/tasks			
		if(not ret):
			self.emit("nothing-found")
		#else:
		#	self.filterEntry.set_type(SearchAddBar.TYPE_FILTER)
		
	def on_nothing_found_cb(self,agenda):
		self.change_view(Agenda.VIEW_ASK)
		fe_text = self.filterEntry.get_text()		

		edit_what = self.wTree.get_widget("edit_what")
		event2add = self.wTree.get_widget("event2add")
		edit_what.set_text(fe_text)
		#when localizing, please consider: http://de.wikipedia.org/wiki/Anf%C3%BChrungszeichen#Andere_Sprachen
		event2add.set_markup(_('<b>“%s”</b> is not on your list') % fe_text)

	def exit_activate_cb(self,widget,data = None):
		"""
		popup_menu_exit handler
		"""
		self.appointments.stop()
		self.window.hide()

	def on_appointments_closed(self,appointments):
		"""
		called after appointment's "close" event is received
		"""
		if(self.statusIcon):
			self.statusIcon.set_visible(False)
		else:
			pass
		try:
			gtk.main_quit()
		except:
			pass				
	def main_delete_event_cb(self,event,data):
		"""delete event of the main window"""
		"""just hide, and stop propagating the event"""
		self.status_icon_click_cb()
		return True
	def dismiss_error_button_clicked_cb(self,widget):
		self.dismissErrors()
	def dismissErrors(self):
		self.errors_label.set_text("")
		self.appointments.clearErrors()
		#self.errorPanel.hide()

	def updateTooltips(self):
		tooltip = "%s" % _(agenda.static.APP_NAME)
		#self.statusIcon.set_tooltip(tooltip)
		
	def error_indicator_button_press_event_cb(self,widget,event=None):
		self.error_indicator.hide()
		#self.errorPanel.show()
	def getErrors(self):
		"""
		A. What went wrong
		   (in non-geek language)
		B. Why it went wrong
		   (in non-geek language)
		C. How I can fix it
		   (preferably in one click)
		"""
		error_text = []
		for error in self.appointments.getErrors():
			try:
				name = error[0]
			except:
				name = ""
			try:
				prov_errors = cgi.escape("\n".join(error[1]))
			except:
				prov_errors = ""
			error_text.append("<b><big>%s</big></b>\n%s\n" %(name,prov_errors))
		return ("\n".join(error_text)).strip()
	def updateErrors(self):
		errors = self.getErrors()
		
		self.errors_label.set_markup(errors)
		if(len(errors) > 0):
			self.error_indicator.show()
		else:
			#self.errorPanel.hide()
			self.error_indicator.hide()
	def setBusy(self, busy = True):
		"""
		update the UI to indicate that we are currently updating...
		"""
		if(busy):
			cursor = gtk.gdk.Cursor(gtk.gdk.WATCH)
			self.progressbar.show()
			self.progressbar.set_busy(True)
			self.updating = True
			gobject.timeout_add(33, self.appointments_progress_cb)
			
		else:
			cursor = None
			self.progressbar.reset()
			self.updating = False
		
		self.refresh_menuitem.set_sensitive(not busy)			
		
		try:
			gdkwin = self.window.window
			if(gdkwin):
				gdkwin.set_cursor(cursor)
		except Exception,e:
			pass
		gtk.gdk.flush()

		
	def refresh_cb(self,widget=None):
		""" refresh """
		if(self.updating):
			return False
		self.appointments.updateCalendars()

		pass
	def on_initialized_cb(self,widget = None):
		"""
		Called at the end of init
		"""
		self.filterEntry.grab_focus()
		
		self.window.resize(max(0,int(self.appointments.get_option('width'))),max(0,int(self.appointments.get_option('height'))))

		screen_w, screen_h = gtk.gdk.screen_width(), gtk.gdk.screen_height()
		self.hide_finished = bool(self.appointments.get_option('hide_finished'))
		
		
		self.install_callback()


	def refresh_callback(self):
		if (self.updating):
			return
		self.refresh_cb()
		self.install_callback()

	def install_callback(self):
		if (self.timeout_refresh != -1):
			gobject.source_remove(self.timeout_refresh)
		
		update_time = int(self.appointments.get_option('refresh')) * 60 * 1000
		if update_time > 0:
			gobject.timeout_add(update_time, self.refresh_callback)		
	def notify(self,event):
		pass
	def remind(self,):
		"""This has to be reimplemented"""
		return
		sql = "SELECT * from Events e, Calendar c WHERE c.hidden = 0 and c.id = e.calendar_id and datetime(e.start_time) > datetime('now') and datetime(e.start_time) < datetime('now','%s minutes') order by e.start_time"
		sql = sql % self.appointments.get_option('reminder')
		toremind = self.appointments.query(sql)
		for row in toremind:
			id = row[0]
			try:
				self.notified_ids.index(id)
				exists = True
			except:
				exists = False
			if(not exists):
				n = pynotify.Notification(row[5],self.getToolipText(row))
				n.set_icon_from_pixbuf("x-calendar")
				n.set_urgency(pynotify.URGENCY_CRITICAL)
				n.set_timeout(pynotify.EXPIRES_NEVER)
				n.show()
				self.notified_ids.append(id)
		self.timeout_alert = gobject.timeout_add(10000, self.remind)
		return False

	def on_filterEntry_changed(self,filterEntry,t = None):
		self.search_entry_activate_cb(None,filterEntry)
		if(t == ""):
			self.change_view(Agenda.VIEW_CALENDAR)

	def show_add_item_panel(self,button = None):
		self.change_view(Agenda.VIEW_EDIT)
		pass
	
	def on_repeat_until_date_entry(self,a):
		print a
		
	def addEventBtn_activate_cb(self,t=None):
		self.change_view(Agenda.VIEW_EDIT)


		
	def bind_keybinding(self, binding):
		"""
		Actually bind keybinding
		"""
		if not self._keybinder.bind(binding):
			print "Could not bind to %s. Already in use" % binding
			pass

			
	def _emit_keybinding_activated(self,t,d = None, k = None):
		self.window.toggle_window()
		
	def _setup_keybinder(self):
		#self._gconf.connect("keybinding-changed", self._on_keybinding_changed)
		
		self._keybinder = Keybinder()
		keybinding = self.get_keybinding()
		if (keybinding == None or gtk.accelerator_parse(keybinding) == (0,0)):
			# Keybinding is not set or invalid, set default keybinding
			keybinding = self.DEFAULT_KEYBINDING
			self.set_keybinding(keybinding) # try to save it to Gconf
		else:
			keybinding = self.get_keybinding()
		self.bind_keybinding(keybinding)
		
		self._keybinder.connect("activated", lambda k,t: self._emit_keybinding_activated(t))
	def set_keybinding(self,	accel_name):
		self.appointments.set_option('accelerator', accel_name)
	def get_keybinding(self):
		"""
		Get keybinding
		
		@return: str
		"""
		#return self._gconf.get_keybinding()
		return self.appointments.get_option('accelerator')
	def appointments_calendars_updated_cb(self,appointments, finisheddt):
		"""
		called whenever the calendars were updated
		"""
		self.setBusy(False)

	def appointments_updating_calendars(self,appointments, startdt):
		self.setBusy(True)
		#it would be nice to update the status icon here as well
	def appointments_updating_tick(self,appointments,progress,time):
		#while gtk.events_pending():
		#	gtk.main_iteration(False)
		pass
	def appointments_progress_cb(self):
		if(self.updating):
			while gtk.events_pending():
				gtk.main_iteration(False)
		return self.updating
	def appointments_updating_provider(self,appointments,provider_updater):
		text =  provider_updater.provider.Plugin_Name
		self.progressbar.set_text(text)
		while gtk.events_pending():
			gtk.main_iteration(False)
			
	def event_store_updated(self,self2,event_store):
		"""
		catched if the event store was updated
		"""
		#this is to prevent multiple redraws
		print "I was aksed to redraw"


